<!--
PAGE DOCUMENTATION:
==================
This page is called via Ajax call and is used to perform the sending process.
(including using FB API to perform FB features and DB updating).

Parameters that can be sent to this page:
----------------------------------------
index - Value: the DB index of the message sent.
ids - an array containing FB ids of the friends the user picked to send the message to.
-->
<?php
	require_once 'appinclude.php';
	require_once 'sqlLib.php';
	require_once 'logsLib.php';
	require_once 'generalLib.php';

$currentPage = 'test';
$user_id = $facebook->user;
$sqlDb = new mysqli("localhost", "root", "", "messages");
$sqlDb->query('SET NAMES utf8');
/* check connection */
if (mysqli_connect_errno()) {
	documentError($user_id,$currentPage,"Connect to MYSQL failed: ".mysqli_connect_error());
	printErrorMsg("connecting to the database");
} else {
	logMysqliConnectionOpened($user_id,$currentPage);
	/* user pressed the send button*/
	if (!isset($_REQUEST['index']))	{
		documentError($user_id,$currentPage,"Not enough parameters for page send.php: send was pressed, but no index passed.");
		$sqlDb->close();
		logMysqliConnectionClosed($user_id,$currentPage);
		logRedirection($user_id, "error.php?action=send",$currentPage);
		redirectFromDialogBox("error","error.php","action","send");
		//echo "<fb:redirect url=\"error.php?action=send\" />";
	} else {
		/* get parameters */
		$index = $_REQUEST['index'];
		if(!isset($_REQUEST['ids'])) {
			/* user didn't choose any recipients */
			echo "<fb:error>
						<fb:message>You didn't choose anybody!</fb:message>
						You must choose at least one friend to send this message to, or the \"cancel\" option.
					</fb:error>";
			/*
			$message_name=getColumnData($sqlDb,"messages_data",$index,'message_name') ;
			if ($message_name==-13) {
				documentError($user_id,$currentPage,"getColumnData failed: messages_data,".$index.",message_name");
				$sqlDb->close();
				logMysqliConnectionClosed($user_id,$currentPage);
				logRedirection($user_id, "error.php?action=send",$currentPage);
				echo "<fb:redirect url=\"error.php?action=send\" />";
			}
			*/
		} else {
			/* all input needed to perform send is ok */
			$recipientsArr = ($_REQUEST['ids']);			
			/* get data of message from DB */
			if(($rowDetail = getmessageFullData($sqlDb,$index))!=-1) {
				logFunctionCall($user_id, "getmessageFullData", "sqlDb,".$index, $rowDetail,$currentPage);
				$message_name = $rowDetail['message_name'];
				$filename = $rowDetail['filename'];
			} else {
				documentError($user_id,$currentPage,"getmessageFullData failed: index: ".$index);
				$sqlDb->close();
				logMysqliConnectionClosed($user_id,$currentPage);
				logRedirection($user_id, "error.php?action=send",$currentPage);
				redirectFromDialogBox("error","error.php","action","send");
				//echo "<fb:redirect url=\"error.php?action=send\" />";
			}
			
			/* perform send process (TA DA DA DAM!) */
			
			/* create new entries in DB for all recipients: */
			$dataArr = createMsgDataArr($message_name,$user_id,$recipientsArr,$filename);
			logFunctionCall($user_id, "createMsgDataArr",$message_name.','.$user_id.','.$recipientsArr.','.$filename,$dataArr,$currentPage);
			if (!($rowsRes = enterSeveralMsgRow($sqlDb,$dataArr))) {
				documentError($user_id,$currentPage,"enterSeveralMsgRow failed");
				$sqlDb->close();
				logMysqliConnectionClosed($user_id,$currentPage);
				logRedirection($user_id, "error.php?action=send",$currentPage);
				redirectFromDialogBox("error","error.php","action","send");
				//echo "<fb:redirect url=\"error.php?action=send\" />";
			} else {
				logFunctionCall($user_id, "enterSeveralMsgRow", "sqlDb,".$dataArr,$rowsRes,$currentPage);
			}			
			$recipientsWithApp = "";
			$recipientsWithOut = "";
			$failList = "";
			
			/* create full recipients list: */
			$userIdsList = implode(",",$recipientsArr);
			
			/* find out which users have the application: */
			try {
				$user_details = $facebook->api_client->users_getInfo($userIdsList, array('has_added_app'));
			} catch (Exception $ex) {
				documentError($user_id,$currentPage,"FaceBook Exception: ".$ex);
				printErrorMsg("sending. Your friends will receive your message if they have added (or will add) VoiceMessanger");
			}
			logFunctionCall($user_id, "facebook->api_client->users_getInfo", "(".$user_details."),array('has_added_app')", $user_details,$currentPage);			
			if ($rowsRes>0) {
				/* do this only if DB update was successful */
				
				/* devide the recipients to 2 lists: users with app and users without */
				for($i=0;$i<count($recipientsArr);$i++) {
					$recipient_id = $recipientsArr[$i];
					if ($user_details[$i]['has_added_app']==1){ //friend has added the app
						
						/* add to $recipientsWithApp: */
						if ( $recipientsWithApp != "" )	{
							$recipientsWithApp .= ",";
						}
						$recipientsWithApp .= $recipient_id;
						
						/* update the recipient profile */
						/* get number of new messages for recipient: */
						if (($numberOfNewMessages = countMessages($sqlDb,$recipient_id,"unread"))==-1) {
							documentError($user_id,$currentPage,"countMessages failed - user_id: $recipient_id, unread");
							printErrorMsg("updating your profile box. It may not be updated");
						} else {
							logFunctionCall($user_id,'countMessages','sqlDb,'.$recipient_id.',unread',$numberOfNewMessages,$currentPage);
						}
						/* get number of messages sent from recipient: */
						if (($numberOfSentMessages = countMessages($sqlDb,$recipient_id,"sent"))==-1) {
							documentError($user_id,$currentPage,"countMessages failed - user_id: $recipient_id, sent");	
							printErrorMsg("updating your profile box. It may not be updated");
						} else {
							logFunctionCall($user_id, 'countMessages', 'sqlDb,'.$recipient_id.',sent', $numberOfSentMessages,$currentPage);
						}
						if (!(profileBox($recipient_id, $numberOfNewMessages, $numberOfSentMessages, $facebook))){
							documentError($user_id,$currentPage,"profileBox failed - user_id: $recipient_id");
							printErrorMsg("updating your profile box. It may not be updated");
						}
					} else { //friend has NOT added the app
						/* add to $recipientsWithOut: */
						if ( $recipientsWithOut != "" )	{
							$recipientsWithOut .= ",";
						}
						$recipientsWithOut .= $recipient_id;
					}
				}
		
				/* send an Email to all recipients with the app: */
				if ($recipientsWithApp!="") {
					$subject = "Someone sent you a new VoiceMessage using Voice Messenger!";
					$content = <<<FBML
<fb:name uid="$user" shownetwork="false"/> dedicated a new VoiceMessage for you.
<a href='http://apps.facebook.com/voicemessenger/'>Let's hear it!</a>
FBML;
					try {
						$facebook->api_client->notifications_sendEmail($recipientsWithApp, $subject, "", $content);
					} catch (Exception $ex) {
						documentError($user_id,$currentPage,"FaceBook Exception: ".$ex);
					}
					logFunctionCall($user_id, "facebook->api_client->notifications_sendEmail", $recipientsWithApp.','.$subject.",\"\",".$content, NULL,$currentPage);
				}
				
				/* send a notification (to all recipients): */
				$notification = <<<FBML
sent you a new VoiceMessage using Voice Messenger!
<a href='http://apps.facebook.com/voicemessenger/'>Would you like to hear it? (yes)</a>
FBML;
				try {
					$facebook->api_client->notifications_send($userIdsList,$notification);
				} catch (Exception $ex) {
					documentError($user_id,$currentPage,"FaceBook Exception: ".$ex);
				}
				logFunctionCall($user_id, "facebook->api_client->notifications_send", $userIdsList.','.$notification, NULL,$currentPage);
				
				/* publish news feed (to user only): */
				$title_template = "{actor} sent {target} a new VoiceMessage!";
				$body_template = "{target} can now hear the clear and natural voice of {actor}.";
				$body_general = "<a href='http://apps.facebook.com/voicemessenger/'>You can send a VoiceMessage ,too!</a>";
				$target_ids = $userIdsList;
				try {
					$feed_publishTemplatizedAction = $facebook->api_client->feed_publishTemplatizedAction($title_template,"",$body_template,"",$body_general,null,null,null,null,null,null,null,null,$target_ids);
				} catch (Exception $ex) {
					documentError($user_id,$currentPage,"FaceBook Exception: ".$ex);
				}
				logFunctionCall($user_id, "facebook->api_client->feed_publishTemplatizedAction", $actor_id.','.$title_template.",\"\",".$body_template.",\"\",".$body_general.",null,null,null,null,null,null,null,null,".$target_ids, $feed_publishTemplatizedAction,$currentPage);		
			
				/* update the sender profile */
				
				/* get number of new messages for sender: */
				if (($numberOfNewMessages = countMessages($sqlDb,$user_id,"unread"))==-1) {
					documentError($user_id,$currentPage,"countMessages failed - user_id: $user_id, unread");
					printErrorMsg("updating your profile box. It may not be updated");
				} else {
					logFunctionCall($user_id,'countMessages','sqlDb,'.$user_id.',unread',$numberOfNewMessages,$currentPage);
				}
				/* get number of messages sent from sender: */
				if (($numberOfSentMessages = countMessages($sqlDb,$user_id,"sent"))==-1) {
					documentError($user_id,$currentPage,"countMessages failed - user_id: $user_id, sent");	
					printErrorMsg("updating your profile box. It may not be updated");
				} else {
					logFunctionCall($user_id, 'countMessages', 'sqlDb,'.$user_id.',sent', $numberOfSentMessages,$currentPage);
				}
				if (!(profileBox($user_id, $numberOfNewMessages, $numberOfSentMessages, $facebook))){
					documentError($user_id,$currentPage,"profileBox failed - user_id: $user_id");
					printErrorMsg("updating your profile box. It may not be updated");
				}
		
				/* close MySQLI connection: */
				$sqlDb->close();
				
				/* for all recipients without the app - ask to invite: */
				if ($recipientsWithOut != "") {
					echo "still here... just a few more seconds.";
					redirectFromDialogBox("noApp","send.php","noApp","$recipientsWithOut");
/*					echo "<form id=\"noApp\" action=\"hello2.php\" method=\"post\">
						<input type=\"hidden\" name=\"noApp\" value=$recipientsWithOut >
						<input type=\"hidden\" name=\"fail\" value=$failList>
						</form>
						<script>
						document.getElementById('noApp').submit();
						</script>
						";
*/
//					if (!(inviteRecipients($recipientsWithOut, $user_id, $facebook, $failList))) {
//						documentError($user_id,$currentPage,"inviteRecipients failed - user_id: $user_id, friends: $recipientsWithOut");
//					} 
//					exit();
				} else {
					//redirect to next page:
					echo "still here... just a few more seconds.";
					logRedirection($user_id,"sendMessage.php?success=all",$currentPage);
					redirectFromDialogBox("success","sendMessage.php","success","all");
/*
					echo "<form id=\"success\" action=\"sendMessage.php\" method=\"post\">
						<input type=\"hidden\" name=\"success\" value=\"all\">
						</form>
						<script>
						document.getElementById('success').submit();
						</script>
						";
*/
					//echo "<fb:redirect url=\"sendMessage.php?success=all\" />";
				}
			} else {
				$failList = $userIdsList;
				//redirect to next page:
				logRedirection($user_id,"sendMessage.php?success=$failList",$currentPage);
				redirectFromDialogBox("failure","sendMessage.php","success","$failList");
/*
				echo "<form id=\"failure\" action=\"sendMessage.php\" method=\"post\">
					<input type=\"hidden\" name=\"success\" value=$failList>
					</form>
					document.getElementById('failure').submit();
					";
*/
				//echo "<fb:redirect url=\"sendMessage.php?success=$failList\" />";
			}
		}
	}
}



?>